<template>
  <div class="source-wrap scene-edit-box">
	  <div class="top-title">
			<span>渲染部署节点(登记渲染节点)</span>
			<div>
				<input type="text"  v-model="keywords" placeholder="请输入名称检索" @keydown="handleSearch"/>
			</div> 
	  </div>
	  <div class="source-box" style="width: 100%;">
		<div class="list-wrap">
			<div class="float scroll min" style="height: 100%;">
				<el-scrollbar style="width: 100%;">
					<el-table
					  :v-loading="loading"
					  :data="tableData"
					  row-key="id"
					  style="width: 100%; margin-bottom: 5px;height: calc(100% - 0px);"
					>
						<el-table-column type="expand">
						  <template #default="props">
							  
						  <div style="margin-bottom: 1px;margin-top: -6px;">
							<el-table :data="props.row.signallings" >
							<el-table-column label="渲染器">
								<template #header>
									<div class="head-r">
										<div class="head-r-title"><span>信令服务</span></div>
										<div class="head-r-tool">
											<el-tooltip
											  class="box-item"
											  effect="dark"
											  content="同步"
											  placement="top"
											>
												<el-button
												  type="primary"
												  link
												  size="small"
												  @click.stop="handleForSynSignalling(props.row)"
												>
												  <i-ep-refresh />
												</el-button>
											</el-tooltip>
										</div>
										
									</div>
								</template>
								<el-table-column label="IP" prop="streamerIp" >
									<template #default="scope"><el-input v-model="scope.row.streamerIp" placeholder="" @change="handleForSignalling(scope.row)" /></template>
								</el-table-column>
								<el-table-column label="UE客户端管理端口" prop="streamerPort" >
									<template #default="scope">
										  <el-input-number
											v-model="scope.row.streamerPort"
											controls-position="right"
											style="width: 100%;"
											@change="handleForSignalling(scope.row)"
										  />
									</template>
								</el-table-column>
								<el-table-column label="WEB/APP端管理端口" prop="playerPort" >
									<template #default="scope">
										  <el-input-number
											v-model="scope.row.playerPort"
											controls-position="right"
											style="width: 100%;"
											@change="handleForSignalling(scope.row)"
										  />
									</template>
								</el-table-column>								
								<el-table-column label="UE客户端超时关闭" prop="streamerIdleTimeout" >
									<template #default="scope">
										  <el-input-number
											v-model="scope.row.streamerIdleTimeout"
											controls-position="right"
											style="width: 100%;"
											:min="5"
											:max="6000"
											@change="handleForSignalling(scope.row)"
										  />
									</template>
								</el-table-column>
							</el-table-column>
							</el-table>
						  </div>
							  
							<div style="margin-bottom: 1px;">
							  <el-table :data="props.row.children" >
								<el-table-column label="显卡列表">
									<template #header>
										
										<div class="head-r">
											<div class="head-r-title"><span>显卡列表</span></div>
											<div class="head-r-tool">
												<el-tooltip
												  class="box-item"
												  effect="dark"
												  content="同步"
												  placement="top"
												>
													<el-button
													  type="primary"
													  link
													  size="small"
													  @click.stop="handleForSynGPU(props.row)"
													>
													  <i-ep-refresh />
													</el-button>
												</el-tooltip>
											</div>
											
										</div>
									</template>
									<el-table-column label="序号" prop="index" />
									<el-table-column label="型号" prop="name" />
									<el-table-column label="显存" prop="memoryTotal" />
									<el-table-column label="路数(重启后生效)" prop="limit">
										<template #default="scope">
											  <el-input-number v-model="scope.row.limit" :min="-1" :max="4" @change="handleChangeForLimit(scope.row)" style="width: 100%;" />
										</template>
									</el-table-column>
								</el-table-column>
							  </el-table>
							</div>
							
							<div >
							  <el-table :data="props.row.relays" >
								<el-table-column label="中继服务">
									<template #header>
										<div class="head-r">
											<div class="head-r-title"><span>中继服务</span></div>
											<div class="head-r-tool">
												<el-tooltip
												  class="box-item"
												  effect="dark"
												  content="同步"
												  placement="top"
												>
													<el-button
													  type="primary"
													  link
													  size="small"
													  @click.stop="handleForSynSFU(props.row)"
													>
													  <i-ep-refresh />
													</el-button>
												</el-tooltip>
											</div>
											
										</div>
									</template>
									
									<el-table-column label="内网IP" prop="ip" >
										<template #default="scope">
											<el-input v-model="scope.row.ip" placeholder="请输入ip" @change="handleAgentRelay(scope.row)" />
										</template>
									</el-table-column>
									
									<el-table-column label="中转服务IP" prop="stunIp" >
										<template #default="scope">
											<el-input v-model="scope.row.stunIp" placeholder="请输入ip" @change="handleAgentRelay(scope.row)" />
										</template>
									</el-table-column>
									
									<el-table-column label="中转服务端口" prop="stunPort">
										<template #default="scope">
											  <el-input-number
												v-model="scope.row.stunPort"
												controls-position="right"
												style="width: 100%;"
												@change="handleAgentRelay(scope.row)"
											  />
										</template>
									</el-table-column>
									
									
									<el-table-column label="穿透服务IP" prop="ip" >
										<template #default="scope">
											<el-input v-model="scope.row.turnIp" placeholder="请输入ip" @change="handleAgentRelay(scope.row)" />
										</template>
									</el-table-column>
									

									<el-table-column label="穿透服务端口" prop="turnPort">
										<template #default="scope">
											  <el-input-number
												v-model="scope.row.turnPort"
												controls-position="right"
												style="width: 100%;"
												@change="handleAgentRelay(scope.row)"
											  />
										</template>
									</el-table-column>
									
									<el-table-column label="中转穿透服务" >
										<template #default="scope">
											<el-switch
												v-model="scope.row.enabled"
												inline-prompt
												active-text="是"
												inactive-text="否"
												active-value="0"
												inactive-value="-1"
												@click="handleAgentRelay(scope.row)"
											/>
										</template>
									</el-table-column>
								</el-table-column>
							  </el-table>
							</div>
							
						  </template>
						</el-table-column>
					
						<el-table-column prop="name" label="名称"  />
						<el-table-column prop="id" label="Licence"  width="280">
							<template #default="scope">
								<el-tooltip
								  class="box-item"
								  effect="dark"
								  content="复制"
								  placement="top"
								>
									<p @click="copyInfo(scope.row)">{{scope.row.id}}</p>
								</el-tooltip>
							</template>
						</el-table-column>
						<el-table-column prop="ip" label="IP" width="180" />
						<el-table-column label="CPU" width="80">
							<template #default="scope">
								{{scope.row.cpuTotal}}核 
							</template>
						</el-table-column>
						<el-table-column prop="gpuTotal" label="GPU" width="80"  />
						<el-table-column label="内存" >
							<template #default="scope">
								{{scope.row.memoryTotal}}
							</template>
						</el-table-column>
						<el-table-column label="磁盘" >
							<template #default="scope">
								<div style="display: block;">
									{{scope.row.diskFree}}可用,共:{{scope.row.diskTotal}}
								</div>
							</template>
						</el-table-column>
						<el-table-column label="同步时间" prop="modifyTime" />
						<el-table-column align="center" label="状态">
							<template #default="scope">
								
								<el-tooltip
								  class="box-item"
								  effect="dark"
								  content="此操作影响节点接入"
								  placement="top"
								>
									<el-switch
										v-model="scope.row.status"
										inline-prompt
										active-text="正常"
										inactive-text="禁用"
										active-value="0"
										inactive-value="-1"
										@change="change(scope.row)"
									/>
								</el-tooltip>
							</template>
						</el-table-column>
						
						<el-table-column fixed="right" align="center" label="操作">
							<template #header>
								<el-button v-hasPerm="['admin:add']"  type="primary" plain link :icon="Plus"  @click.stop="openDialog(null,'add')">渲染节点</el-button>
							</template>
						  <template #default="scope">
							  
								<el-tooltip
								  class="box-item"
								  effect="dark"
								  content="新增子账号"
								  placement="top"
								>
									<el-button
									  v-show="scope.row.pid=='-1' && scope.row.username!='administrator' "
									  type="primary"
									  link
									  size="small"
									  @click.stop="openDialog(scope.row,'add')"
									>
									  <i-ep-plus />
									</el-button>
								</el-tooltip>
								
								<el-tooltip
								  class="box-item"
								  effect="dark"
								  content="编辑"
								  placement="top"
								>
									<el-button
									  v-show="scope.row.username!='administrator' "
									  type="primary"
									  link
									  size="small"
									  v-hasPerm="['admin:add']"
									  @click.stop="openDialog(scope.row,'edit')"
									>
									  <i-ep-edit />
									</el-button>
								</el-tooltip>
								
								<el-tooltip
								  class="box-item"
								  effect="dark"
								  content="删除"
								  placement="top"
								>
									<el-button
									  v-show="scope.row.username!='administrator' "
									  type="primary"
									  link
									  size="small"
									  v-hasPerm="['admin:add']"
									   @click.stop="handleDelete(scope.row)"
									  ><i-ep-delete />
									</el-button>
								</el-tooltip>
						  </template>
						</el-table-column>
					</el-table>
				</el-scrollbar>
			</div>
		</div>	
	</div>
	<el-dialog
	  v-model="dialog.visible"
	  :title="dialog.title"
	  destroy-on-close
	  append-to-body
	  width="750px"
	  @close="closeDialog"
	>
	
	
	<el-form
	  ref="userFormRef"
	  :model="userFormData"
	  :rules="userFormRules"
	  label-width="100px"
	>
		<el-form-item label="名称" prop="name">
		  <el-input v-model="userFormData.name" placeholder="请输入名称" />
		</el-form-item>
		<el-form-item label="IP" prop="ip">
		  <el-input v-model="userFormData.ip" placeholder="请输入IP" />
		</el-form-item>
	</el-form>

	<template #footer>
	  <div class="dialog-footer">
	    <el-button type="primary" @click="submitForm"  :loading="loading">确 定</el-button>
	    <el-button @click="closeDialog" :loading="loading">取 消</el-button>
	  </div>
	</template>

	</el-dialog>
	<AccreditDialog ref="accreditDialog"></AccreditDialog>
	
  </div>
</template>
<script lang="ts" setup>
	import AccreditDialog from "./components/AccreditDialog.vue";
	import { reactive, ref } from 'vue'
	import type {FormRules } from 'element-plus'
 	import {
	  Plus
	} from '@element-plus/icons-vue' 
	
	import useClipboard from 'vue-clipboard3'

	import { listForAgent,saveForAgent,deleteForAgent,limitForAgent,saveForAgentRelay,synForAgentRelay,synForAgentGPU,saveForAgentSignalling,synForAgentSignalling} from "@/api/agent";
	const tableData=ref([]);
	const keywords=ref('');
	const accreditDialog=ref();
	const { toClipboard } = useClipboard()


	
	const loading = ref(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	
	const userFormRef=ref();
	
	const userFormRules=reactive<FormRules>({
	  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
	  ip: [{ required: true, message: "请输入IP", trigger: "blur" }],
	});
	
	const userFormData=reactive<Object>({
		id:'',
		name:'',
		ip:'',
	})
	
	const load=()=>{
		loading.value=true;
		listForAgent({
			id:'-1',
			name:keywords.value
		})
		.then(({result}) => {
			tableData.value=result
		})
		.catch((e) => {
		})
		.finally(() => {
			loading.value=false;
		});
	}
	
	const copyInfo = async (text:any) => {
	  try {
		await toClipboard(text.id)
		ElMessage.success('复制成功')
	  } catch (e) {
		console.error(e)
		ElMessage.error('复制失败')
	  }
	}

	
	const handleSearch=(e)=>{
		if(e.keyCode == 13) {
			load();
		}
	}
	
	const openDialog=(row:object,type:string)=>{
		if('add'==type){
			dialog.value.visible=true;
			dialog.value.title='新增';
			Object.assign(userFormData, {pid:row?row.id:'-1'});
		}else{
			dialog.value.visible=true;
			dialog.value.title='编辑';
			Object.assign(userFormData, row);
		}
	}
	
	const handleDelete=(row :object)=>{
		ElMessageBox.confirm("确认删除["+row.name+"]吗?", "警告", {
		  confirmButtonText: "确定",
		  cancelButtonText: "取消",
		  type: "warning",
		})
		  .then(() => {
			  loading.value=true;
			  deleteForAgent({
			  	id:row.id
			  })
			  .then(() => {
				load();
				ElMessage.success("删除成功");
			  })
			  .catch((e) => {
			  })
			  .finally(() => {
			  	loading.value=false;
			  });
		  })
		  .catch(() => ElMessage.info("已取消删除"));
	}
	
	const submitForm=()=>{
		userFormRef.value.validate((isValid: boolean) => {
		  if (isValid) {
				loading.value=true;
				saveForAgent(userFormData)
				.then((res) => {
					load();
					ElMessage.success(res.message);
					closeDialog();
				})
				.catch((e) => {
				})
				.finally(() => {
					loading.value=false;
				});
		  }
		});
	}
	
	const change=(row:{id:string,status:string})=>{
		loading.value=true;
		saveForAgent({
			id:row.id,
			status:row.status
		})
		.then((res) => {
			ElMessage.success(res.message);
		})
		.catch((e) => {
		})
		.finally(() => {
			loading.value=false;
		});
	}
	
	//显卡路数限制
	const handleChangeForLimit=(row:any)=>{
		loading.value=true;
		limitForAgent({
			id:row.id,
			agentId:row.agentId,
			index:row.index,
			limit:row.limit,
		})
		.then((res) => {
			ElMessage.success(res.message);
		})
		.catch((e) => {
		})
		.finally(() => {
			loading.value=false;
		});
	}
	
	const handleAgentRelay=(row:any)=>{
		loading.value=true;
		saveForAgentRelay({
			id:row.id,
			ip:row.ip,
			stunIp:row.stunIp,
			turnIp:row.turnIp,
			stunPort:row.stunPort,
			turnPort:row.turnPort,
			enabled:row.enabled
		})
		.then((res) => {
			ElMessage.success(res.message);
		})
		.catch((e) => {
		})
		.finally(() => {
			loading.value=false;
		});
	}
	
	const handleForSynGPU=(row :{id:string})=>{
		ElMessageBox.confirm("确认同步GPU配置信息吗?", "警告", {
		  confirmButtonText: "确定",
		  cancelButtonText: "取消",
		  type: "warning",
		})
		  .then(() => {
			  loading.value=true;
			  synForAgentGPU({
			  	id:row.id
			  })
			  .then(() => {
				ElMessage.success("成功");
			  })
			  .catch((e) => {
			  })
			  .finally(() => {
			  	loading.value=false;
			  });
		  })
		  .catch(() => ElMessage.info("已取消"));
	}
	
	
	const handleForSynSFU=(row :{id:string})=>{
		ElMessageBox.confirm("确认同步中继服务参数吗?", "警告", {
		  confirmButtonText: "确定",
		  cancelButtonText: "取消",
		  type: "warning",
		})
		  .then(() => {
			  loading.value=true;
			  synForAgentRelay({
			  	id:row.id
			  })
			  .then(() => {
				ElMessage.success("成功");
			  })
			  .catch((e) => {
			  })
			  .finally(() => {
			  	loading.value=false;
			  });
		  })
		  .catch(() => ElMessage.info("已取消"));
	}
	
	const handleForSignalling=(row :{id:string})=>{
		loading.value=true;
		saveForAgentSignalling({
			id:row.id,
			streamerIp:row.streamerIp,
			streamerPort:row.streamerPort,
			streamerIdleTimeout:row.streamerIdleTimeout,
			playerIp:row.streamerIp,
			playerPort:row.playerPort
		})
		.then(() => {
			ElMessage.success("成功");
		})
		.catch((e) => {
		})
		.finally(() => {
		loading.value=false;
		});
	}
	
	const handleForSynSignalling=(row :{id:string})=>{
		ElMessageBox.confirm("确认同步信令服务吗?", "警告", {
		  confirmButtonText: "确定",
		  cancelButtonText: "取消",
		  type: "warning",
		})
		  .then(() => {
			  loading.value=true;
			  synForAgentSignalling({
			  	id:row.id
			  })
			  .then(() => {
				ElMessage.success("成功");
			  })
			  .catch((e) => {
			  })
			  .finally(() => {
			  	loading.value=false;
			  });
		  })
		  .catch(() => ElMessage.info("已取消"));
	}
	
	
	
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		resetForm();
	}
	
	/**
	 * 重置表单
	 */
	function resetForm() {
	  userFormRef.value.resetFields();
	  userFormRef.value.clearValidate();
	
	  userFormData.id = "";
	  userFormData.ip = "";
	  userFormData.name= "";
	}
	
	onMounted(() => {
		load();
	});
	
	
</script>
<style scoped>
	:deep(.el-table--enable-row-transition .el-table__body td.el-table__cell){
		background-color: transparent !important;
	}
	:deep(.el-table thead.is-group th.el-table__cell){
		background-color: #2a2d3e;
	}
	:deep(.el-table td.el-table__cell div){
		display: flex;
	}
</style>